#!/usr/bin/env bash
#
# 11-narsil-disk-usage - the disk usage of banner
# Seaton Jiang <hi@seatonjiang.com>
#
# The latest version of Narsil can be found at:
# https://github.com/seatonjiang/narsil
#
# Copyright (C) 2023 Seaton Jiang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

export LC_ALL=C.UTF-8

set -u -o pipefail

mapfile -t DFH < <(df -h -x zfs -x squashfs -x tmpfs -x devtmpfs -x overlay --output=target,pcent,size,used | tail -n+2)

# Colors
G="\033[01;32m"
R="\033[01;31m"
D="\033[39m\033[2m"
N="\033[0m"

echo -e "  [Disk Usage]\n"

for LINE in "${DFH[@]}"; do
    # Get disk usage
    DISK_USAGE=$(echo "${LINE}" | awk '{print $2}' | sed 's/%//')
    USAGE_WIDTH=$((("${DISK_USAGE}"*60)/100))

    # If the usage rate is <90%, the color is green, otherwise it is red
    if [ "${DISK_USAGE}" -gt 90 ]; then
        COLOR="${R}"
    else
        COLOR="${G}"
    fi

    # Print the used width
    BAR="[${COLOR}"
    for ((i=0; i<"${USAGE_WIDTH}"; i++)); do
        BAR+="="
    done

    # Print unused width
    BAR+=${D}
    for ((i="${USAGE_WIDTH}"; i<60; i++)); do
        BAR+="="
    done
    BAR+="${N}]"

    # Output
    echo "${LINE}" | awk '{ printf("Mounted: %-32s %s / %s (%s Used)\n", $1, $4, $3, $2); }' | sed -e 's/^/  /'
    echo -e "${BAR}" | sed -e 's/^/  /'
done
echo
